/*
 * Copyright (c) 2024.  little3201.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *       https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.server.starter.exploiter.service.impl;

import com.server.starter.exploiter.domain.Template;
import com.server.starter.exploiter.dto.TemplateDTO;
import com.server.starter.exploiter.mapper.TemplateMapper;
import com.server.starter.exploiter.repository.TemplateRepository;
import com.server.starter.exploiter.service.TemplateService;
import com.server.starter.exploiter.vo.TemplateVO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.StreamSupport;

@Service
public class TemplateServiceImpl implements TemplateService {

    private final TemplateRepository templateRepository;
    private final TemplateMapper templateMapper;

    public TemplateServiceImpl(TemplateRepository templateRepository, TemplateMapper templateMapper) {
        this.templateRepository = templateRepository;
        this.templateMapper = templateMapper;
    }

    @Override
    public Page<TemplateVO> retrieve(int page, int size, String sortBy, boolean descending, String name) {
        Pageable pageable = pageable(page, size, sortBy, descending);

        if (StringUtils.hasText(name)) {
            return templateRepository.findAllByNameContaining(name, pageable).map(this::convert);
        }
        return templateRepository.findAll(pageable).map(this::convert);
    }

    @Override
    public List<TemplateVO> retrieve(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return templateRepository.findAll().stream().map(this::convert).toList();
        } else {
            return templateRepository.findAllById(ids).stream().map(this::convert).toList();
        }
    }

    @Override
    public TemplateVO fetch(Long id) {
        return templateRepository.findById(id).map(this::convert).orElse(null);
    }

    @Override
    public TemplateVO create(TemplateDTO dto) {
        Template template = convert(dto, Template.class);
        templateRepository.save(template);
        return this.convert(template);
    }

    @Override
    public List<TemplateVO> createAll(Iterable<TemplateDTO> iterable) {
        List<Template> templates = StreamSupport.stream(iterable.spliterator(), false)
                .map(dto -> convert(dto, Template.class)).toList();
        return templateRepository.saveAll(templates).stream().map(this::convert).toList();
    }

    @Override
    public TemplateVO modify(Long id, TemplateDTO dto) {
        Assert.notNull(id, "id must not be null.");

        return templateRepository.findById(id)
                .map(existing -> {
                    Template template = convert(dto, existing);
                    template = templateRepository.save(template);
                    return this.convert(template);
                })
                .orElseThrow();
    }

    @Override
    public void remove(Long id) {
        Assert.notNull(id, "id must not be null.");

        templateRepository.deleteById(id);
    }

    @Override
    public boolean exists(String name, String suffix, String version, Long id) {
        return templateMapper.countByNameAndSuffixAndVersionAndIdNot(name, suffix, version, id) > 0;
    }

    @Override
    public boolean enable(Long id) {
        return templateRepository.updateEnabledById(id);
    }

    /**
     * 类型转换
     *
     * @param template 信息
     * @return VO 输出对象
     */
    private TemplateVO convert(Template template) {
        TemplateVO vo = convert(template, TemplateVO.class);
        vo.setLastModifiedDate(template.getLastModifiedDate().orElse(null));
        return vo;
    }
}
